package com.qf.helloMybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * @author 钻五大人
 * @date 2022/4/21 14:46
 */
public class MyBatisUtil {

    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> Tl =new ThreadLocal<>();

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 打开会话的方法
    public static SqlSession openSession(){
        SqlSession session = Tl.get();
        if(Objects.isNull(session)){
            session = factory.openSession();
            Tl.set(session);
        }
        return session;
    }

    // 关闭会话的方法
    public static void closeSession(){
        SqlSession session = openSession();
        if (Objects.nonNull(session)) {
            session.close();
            Tl.remove();
        }
    }

    // 提交事务
    public static void commit(){
        SqlSession session = openSession();
        session.commit();
        closeSession();
    }

    // 回滚事务
    public static void rollback(){
        SqlSession session = openSession();
        session.rollback();
        closeSession();
    }

    // 获取接口的方法
    public static <T extends Object> T getMapper(Class<T> clazz){
        SqlSession session = openSession();
        return session.getMapper(clazz);
    }
}
